import { Config } from 'config.js';
import { Token } from './token.js';
Date.prototype.cartFormat = function (fmt) { 
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
};
class Base {
  constructor() {
    'use strict';
    this.restUrl = Config.restUrl;
    this.qiniuBaseUrl = Config.qiniuBaseUrl;
    this.nowV = Config.nowV
  }

  /**
   *封装请求wx.request统一处理路径config
  */
  request(params, reFetch) {
    var that = this;
    let url = that.restUrl + params.url;
    let sessionId = wx.getStorageSync('sessionId')
    // console.log('sessionId', sessionId)
    if (Object.keys(params && params.data).length) {
        var wxSid = wx.getStorageSync('wxSid');
        var wxUid = wx.getStorageSync('wxUid');
        var storeNo = wx.getStorageSync('storeNo');
        var userStatus = wx.getStorageSync('userStatus');
        if (wxSid && wxUid && wxSid != "" && wxUid != "") {
            params.data.data.wxSid = wxSid;
            params.data.data.wxUid = wxUid;
            params.data.data.storeNo = storeNo;
            params.data.data.tradeType = 'JSAPI';
            params.data.data.userStatus = userStatus;
        } else {
            let app = getApp();
            // app.getUserSetting();
        }

    }
    let requestObj = {
      url: url, //仅为示例，并非真实的接口地址
      data: params.data,
      method: params.type ? params.type : 'POST',
      header: {
        'content-type': 'application/json', // 默认值
        'sessionId': sessionId
      },
      success: (res) => {
        var code = res.statusCode.toString();
        if (code.charAt(0) == '2') {
            let code = res.data.code;
          if (res.data.status) {
              params.sCallback && params.sCallback(res.data);
          } else if (code == 500 && res.data.message === '认证错误'){
               wx.showToast({
                  title: `认证错误`,
                  icon: 'success',
                  duration: 1500,
                  success(){
                    setTimeout(()=>{
                        wx.reLaunch({
                            url: '/pages/getUserInfo/getUserInfo',
                        })
                    },1500)
                  }
               })
                
          } else {
            params.eCallback && params.eCallback(res.data);
          }
        } else {
          if (code == '401' && !noFetch) {
            that._refetch(params);
          }

          params.eCallback && params.eCallback(res.data);
          that._processErr(res);
        }
      }, fail: (err) => {

        params.eCallback && params.eCallback(err);
        this._processErr(err);
      }
    }
    wx.request(requestObj);
  }

  _processErr(res) {
    console.log(res);
    wx.showToast({
      title: `请求服务错误`,
      icon: 'success',
      duration: 1000
    })
  }
  _refetch(param) {
    var token = new Token(), that = this;
    token.getTokenFromServer((token) => {
      that.request(param, true);
    });
  }
  //普通接口调用，post请求
  commonRequest(url, options = {}, callback) {
    var that = this;
    var parames = {
      url: url,
      data: { "data": options },
      sCallback: data => {
        callback && callback(data);
      },
      eCallback: data => {
        callback && callback(data);
      }
    };
    this.request(parames);
  }

  /*获得元素上的绑定的值*/
  getDataSet(event, key) {
    return event.currentTarget.dataset[key];
  };
  /* 存储formId 以供发送模板消息 */
  dealFormIds(formId) {
    let formIds = wx.getStorageSync('formIds');//获取全局数据中的推送码gloabalFomIds数组
    if (!formIds) formIds = [];
    let data = {
      formId: formId,
      createTime: parseInt(new Date().getTime()), //计算7天后的过期时间时间戳
      wxUid: wx.getStorageSync('wxUid'),
      storeNo: wx.getStorageSync('storeNo')
    }
    formIds.push(data);//将data添加到数组的末尾
    wx.setStorageSync('formIds', formIds) //保存推送码并赋值给全局变量
  }


  // 弹窗
  showMyTip({ _this = {}, title = "请输入弹窗内容", isShow = isShowPopup, tip = tip } = {}) {
    let that = _this;
    let isShowPopup = isShow;
    let status = that.data.isShowPopup;
    if (!status) {
      that.setData({
        isShowPopup: true,
        tip: title
      });
      setTimeout(() => {
        that.setData({
          isShowPopup: false
        });
      }, 3000);
    }

  }


  // 模态框
  showModal({ _title = '提示', _content = '这是一个模态弹窗', confirm = null, cancel = null } = {}) {
    wx.showModal({
      title: _title,
      content: _content,
      success: function (res) {
        if (res.confirm) {
          confirm && confirm(res);
        } else if (res.cancel) {
          cancel && cancel(res);
        }
      }
    });
  }
  formate(fmt, data) {
      var data = data ? data : 'yyyy-MM-dd hh:mm:ss'
      return (new Date(fmt)).cartFormat(data)
  }
}
module.exports = {
  Base
}